package com.mxpio.erp.quality.controller;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.inventory.entity.VInvLotStock;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.order.service.OrderService;
import com.mxpio.erp.common.quality.entity.UnqualifiedDisposal;
import com.mxpio.erp.common.quality.entity.UnqualifiedDisposalLine;
import com.mxpio.erp.common.quality.service.UnqualifiedDisposalLineService;
import com.mxpio.erp.common.quality.service.UnqualifiedDisposalService;
import com.mxpio.erp.common.vo.UnqualifiedDisposalAuditVO;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Tag(name = "UnqualifiedDisposalController", description = "不良品处理单接口")
@RestController
@RequestMapping("/erp/quality/ud/")
public class UnqualifiedDisposalController {

    @Autowired
    private UnqualifiedDisposalService unqualifiedDisposalService;

    @Autowired
    private UnqualifiedDisposalLineService unqualifiedDisposalLineService;

    @Autowired
    private OrderService orderService;

    @GetMapping("list")
    @Operation(summary = "不良品处理单列表", description = "获取不良品处理单列表（无分页）", method = "GET")
    public Result<List<UnqualifiedDisposal>> list(@Parameter(description = "查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<UnqualifiedDisposal> orders = unqualifiedDisposalService.list(UnqualifiedDisposal.class, criteria);
        return Result.OK(orders);
    }

    @GetMapping("page")
    @Operation(summary = "不良品处理单列表", description = "获取不良品处理单列表（分页）", method = "GET")
    public Result<Page<UnqualifiedDisposal>> page(@Parameter(description = "查询参数") Criteria criteria, @Parameter(description = "每页条数") Integer pageSize, @Parameter(description = "页号") Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<UnqualifiedDisposal> pageOrder = unqualifiedDisposalService.listPage(UnqualifiedDisposal.class, page, criteria);
        return Result.OK(pageOrder);
    }

    @GetMapping("list/{bizNo}")
    @Operation(summary = "根据bizNo获取不良品处理单", description = "根据bizNo获取不良品处理单", method = "GET")
    public Result<UnqualifiedDisposal> getById(@PathVariable(name = "bizNo", required = true) String bizNo) {
        UnqualifiedDisposal scrapOutApply = unqualifiedDisposalService.getById(UnqualifiedDisposal.class, bizNo);
        return Result.OK(scrapOutApply);
    }


    @RequestMapping("save")
    @Operation(summary = "保存不良品处理单", description = "保存不良品处理单")
    public Result<UnqualifiedDisposal> save(@RequestBody UnqualifiedDisposal disposal) {
        unqualifiedDisposalService.save(disposal,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof UnqualifiedDisposalLine){
                    UnqualifiedDisposal scrapOutApply = context.getParent();
                    ((UnqualifiedDisposalLine) o).setBizNo(scrapOutApply.getBizNo());
                }
                return true;
            }
        });
        return Result.OK(disposal);
        /*try {
            return unqualifiedDisposalService.saveWithCheck(scrapOutApply);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }*/
    }

    @RequestMapping("save_and_pass")
    @Operation(summary = "保存并审核通过不良品处理单", description = "保存并审核通过不良品处理单")
    public Result<UnqualifiedDisposal> saveAndPass(@RequestBody UnqualifiedDisposal scrapOutApply) {
        try {
            return unqualifiedDisposalService.saveAndPass(scrapOutApply);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }


    @DeleteMapping("remove/{bizNo}")
    @Operation(summary = "根据bizNo删除不良品处理单", description = "根据bizNo删除不良品处理单,多个bizNo用英文逗号分隔", method = "DELETE")
    public Result<UnqualifiedDisposal> remove(@PathVariable(name = "bizNo", required = true) String bizNos) {
        String[] bizNo = bizNos.split(",");
        for (String key : bizNo) {
            Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
            unqualifiedDisposalLineService.removeBatch(UnqualifiedDisposalLine.class, c);
            unqualifiedDisposalService.remove(UnqualifiedDisposal.class, key);
        }
        return Result.OK();
    }

    @PutMapping("open/{bizNo}")
    @Operation(summary = "打开不良品处理单", description = "打开不良品处理单", method = "PUT")
    public Result<? extends Order> open(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        UnqualifiedDisposal po = unqualifiedDisposalService.getById(UnqualifiedDisposal.class, bizNo);
        return orderService.updateCloseStatus(po, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{bizNo}")
    @Operation(summary = "关闭不良品处理单", description = "关闭不良品处理单", method = "PUT")
    public Result<? extends Order> close(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        UnqualifiedDisposal po = unqualifiedDisposalService.getById(UnqualifiedDisposal.class, bizNo);
        return orderService.updateCloseStatus(po, OrderStatusEnums.CloseStatus.CLOSED);
    }

    @PutMapping("submit/{bizNo}")
    @Operation(summary = "提交不良品处理单", description = "提交不良品处理单", method = "PUT")
    public Result<? extends Order> submit(@Parameter(description = "业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        return unqualifiedDisposalService.submitOrder(bizNo);
    }

    @RequestMapping("techaudit")
    @Operation(summary = "技术审核", description = "技术审核不良品处理单")
    public Result<UnqualifiedDisposal> techAudit(@RequestBody UnqualifiedDisposalAuditVO auditVO) {
        auditVO.setAuditType("1");//技术审核
        return unqualifiedDisposalService.audit(auditVO);
    }
    @RequestMapping("craftaudit")
    @Operation(summary = "工艺审核", description = "工艺审核不良品处理单")
    public Result<UnqualifiedDisposal> craftAudit(@RequestBody UnqualifiedDisposalAuditVO auditVO) {
        auditVO.setAuditType("2");//技术审核
        return unqualifiedDisposalService.audit(auditVO);
    }
    @RequestMapping("qualityaudit")
    @Operation(summary = "质量审核", description = "质量审核不良品处理单")
    public Result<UnqualifiedDisposal> qualityAudit(@RequestBody UnqualifiedDisposalAuditVO auditVO) {
        auditVO.setAuditType("3");//技术审核
        return unqualifiedDisposalService.audit(auditVO);
    }


    @GetMapping("lotunrefer")
    @Operation(summary = "明细行新增选择批次数据源", description = "明细行新增选择批次数据源（分页）", method = "GET")
    public Result<Page<VInvLotStock>> lotPageUDUnRefer(@Parameter(description = "查询参数") Criteria criteria, @Parameter(description = "每页条数") Integer pageSize, @Parameter(description = "页号") Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<VInvLotStock> vInvLotStocks = unqualifiedDisposalService.lotPageUDUnRefer(page, criteria);
        return Result.OK(vInvLotStocks);
    }

}


